<template>
  <div style="background-color: #f8fafc; font-family: sans-serif; color: #1e293b;  display: flex; flex-direction: column;">
    <!-- 顶部导航栏 -->

    <!-- 主内容区域 -->
    <main style="flex-grow: 1; padding-top: 0.75rem; padding-bottom: 5rem;max-height: 500px;overflow: scroll">
      <!-- 退货申请页面 -->
      <div style="padding: 1.5rem; animation: fadeIn 0.3s ease-in-out;">
        <!-- 产品信息卡片 -->
        <div v-if="productInfo" style="background-color: #ffffff; border-radius: 1rem; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1); margin-bottom: 1rem; overflow: hidden;">
          <!-- 产品信息 -->
          <div style="display: flex; align-items: center; padding: 1rem; border-bottom: 1px solid #e2e8f0;">
            <div style="width: 5rem; height: 5rem; border-radius: 0.5rem; overflow: hidden; margin-right: 1rem; flex-shrink: 0;">
              <img :src="productInfo.product_image || 'https://picsum.photos/200/200?random=1'" :alt="productInfo.product_name" style="width: 100%; height: 100%; object-fit: cover;">
            </div>
            <div>
              <h3 style="font-weight: 500;">{{ productInfo.product_name || '产品名称' }}</h3>
              <div style="display: flex; justify-content: space-between; margin-top: 0.25rem;">
                <div style="font-size: 0.875rem; color: #64748b;">规格: {{ productInfo.product_size || '规格信息' }}</div>
                <div style="font-weight: 700;">¥{{ (Number(productInfo.product_price) || 0).toFixed(2) }}</div>
              </div>
              <div style="display: flex; justify-content: space-between; margin-top: 0.25rem;">
                <div style="font-size: 0.875rem; color: #64748b;">数量: {{ productInfo.back_num || 1 }}</div>
                <div style="font-size: 0.875rem; color: #64748b;">小计: ¥{{ (Number(productInfo.product_price) * (productInfo.back_num || 1)).toFixed(2) }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 退款金额显示 -->
        <div style="background: linear-gradient(to right, #ecfdf5, #d1fae5); border-radius: 1rem; padding: 1rem; margin-bottom: 1rem; border: 1px solid #a7f3d0;">
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <div style="width: 35%;">
              <p style="color: #48bb78;">申请退款金额</p>
              <input
                  type="number"
                  v-model="refundAmount"
                  step="0.01"
                  style="width: 100%; padding: 0.5rem 0.75rem; border: 1px solid #e2e8f0; border-radius: 0.5rem; transition: all 0.2s ease-in-out;"
                  @input="updateRefundAmountDisplay"
                  :disabled="true"
              />
            </div>
<!--            <div style="margin-top: auto;background-color: rgba(34, 197, 94, 0.2); color: #059669; padding: 0.25rem 0.75rem; border-radius: 9999px; font-size: 0.75rem; display: flex; align-items: center;">-->
<!--              <i class="fa-solid fa-info-circle" style="margin-right: 0.25rem;"></i> 按实际退货数量计算-->
<!--            </div>-->
          </div>
          <div style="margin-top: 0.75rem; font-size: 0.875rem; color: #64748b;">
            <i class="fa-solid fa-exclamation-circle" style="margin-right: 0.25rem;"></i> 退款金额将根据实际退货情况计算
          </div>
          <!-- 退货数量 -->
          <div class="form-group" style="margin-bottom: 1rem;">
            <label class="form-label" for="return-quantity" style="display: block; margin-bottom: 0.5rem; font-weight: 500;">退货数量</label>
            <div class="flex items-center" style="display: flex; align-items: center;">
              <nut-input-number v-model="backInput" :min="1" :max="productInfo.back_num" :button-size="35" :input-width="220" @change="changeBack"/>
            </div>
            <p id="return-quantity-error" class="form-error hidden" style="color: #dc2626; margin-top: 0.25rem; font-size: 0.875rem; display: none;">请输入正确的退货数量</p>
          </div>
        </div>

        <!-- 工单信息显示 -->
        <div v-if="workOrders && workOrders.length > 0" style="background-color: #ffffff; border-radius: 1rem; padding: 1rem; margin-bottom: 1rem; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem;">
            <h2 style="font-weight: 700; font-size: 1.125rem;">工单信息</h2>
            <span style="font-size: 0.875rem; color: #64748b;">{{ workOrders.length }}个工单</span>
          </div>
          <div>
            <div v-for="(order, index) in workOrders" :key="order.id || index"
                 style="background-color: #ffffff; border-radius: 0.5rem; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1); padding: 0.75rem; margin-bottom: 0.75rem; border: 1px solid #e2e8f0;">
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <div>
                  <h3 style="font-weight: 500;">{{ order.srv_type || ['量尺工单', '设计工单'][index] }}</h3>
                  <div style="display: flex; align-items: center; margin-top: 0.25rem;">
                    <p style="font-size: 0.875rem; color: #64748b;">工单编号: {{ order.srv_code || ['WO2025061700456', 'WO2025061800789'][index] }}</p>
                  </div>
                </div>
                <div style="display: flex; flex-direction: column">
                  <span :style="[
                    order.status === '待处理' ?
                      { backgroundColor: '#fef3c7', color: '#d97706' } :
                      order.srv_sts === '处理中' ?
                        { backgroundColor: '#f66969', color: '#f3f0f0' } :
                        { backgroundColor: '#d1fae5', color: '#047857' }
                  ]" style="font-size: 0.75rem; padding: 0.125rem 0.5rem; border-radius: 9999px; font-weight: 500; margin-left: 0.5rem;">
                    {{ order.srv_sts || ['待处理', '处理中'][index] }}
                  </span>
                  <span style="font-weight: 700; color: #dc2626;margin-left: auto;margin-right: auto">¥{{ order.srv_amount || '¥0.00' }}</span>
<!--                  <span
                      style="margin-left: 0.5rem; font-size: 0.75rem; color: #dc2626; cursor: pointer; border-bottom: 1px dashed #94a3b8; transition: color 0.2s ease-in-out;"
                      @click="editWorkOrder(index)"
                  >
                    <i class="fa-solid fa-pencil"></i> 编辑
                  </span>-->
                </div>
              </div>
              <div style="margin-top: 0.5rem; font-size: 0.875rem; color: #64748b;">
                <i class="fa-solid fa-clock" style="margin-right: 0.25rem;"></i> 创建时间: {{ order.createTime || ['2025-06-17 14:20', '2025-06-18 10:15'][index] }}
              </div>
              <!-- 工单金额编辑框 (默认隐藏) -->
              <div v-if="editingWorkOrderIndex === index" style="margin-top: 0.5rem;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                  <div style="display: flex; align-items: center;">
                    <span style="font-weight: 700; margin-right: 0.5rem;">¥</span>
                    <input
                        type="number"
                        v-model="workOrders[index].inputAmount"
                        step="0.01"
                        min="0"
                        style="width: 6rem; border: 1px solid #e2e8f0; border-radius: 0.25rem; padding: 0.25rem 0.5rem; text-align: right;"
                    />
                  </div>
                  <div style="display: flex; gap: 0.5rem;">
                    <button
                        style="padding: 0.25rem 0.5rem; font-size: 0.75rem; border: 1px solid #cbd5e1; border-radius: 0.375rem; transition: background-color 0.2s ease-in-out;"
                        @click="cancelWorkOrderEdit(index)"
                    >
                      取消
                    </button>
                    <button
                        style="padding: 0.25rem 0.5rem; font-size: 0.75rem; background-color: #dc2626; color: #ffffff; border-radius: 0.375rem; transition: background-color 0.2s ease-in-out;"
                        @click="saveWorkOrderAmount(index)"
                    >
                      保存
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 退货申请表单 -->
        <div style="background-color: #ffffff; border-radius: 1rem; padding: 1rem; margin-bottom: 1rem; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);">
          <form @submit.prevent="handleSubmit" style="display: flex; flex-direction: column; gap: 1rem;">
            <!-- 退货原因 -->
            <div style="margin-bottom: 1rem;">
              <label style="display: block; font-size: 0.875rem; font-weight: 500; color: #475569; margin-bottom: 0.25rem;" for="return-reason">退货原因</label>
              <select v-model="returnReason" id="return-reason" style="width: 100%; padding: 0.5rem 0.75rem; border: 1px solid #e2e8f0; border-radius: 0.5rem; transition: all 0.2s ease-in-out;">
                <option value="">请选择退货原因</option>
                <option value="质量问题">质量问题</option>
                <option value="尺寸不符">尺寸不符</option>
                <option value="颜色不符">颜色不符</option>
                <option value="不需要了">不需要了</option>
                <option value="其他原因">其他原因</option>
              </select>
              <p v-if="!returnReason" style="font-size: 0.75rem; color: #ef4444; margin-top: 0.25rem;">请选择退货原因</p>
            </div>

            <!-- 退货说明 -->
            <div style="margin-bottom: 1rem;">
              <label style="display: block; font-size: 0.875rem; font-weight: 500; color: #475569; margin-bottom: 0.25rem;" for="return-description">退货说明</label>
              <textarea
                  v-model="returnDescription"
                  rows="2"
                  style=" padding: 0.5rem 0.6rem; border: 1px solid #e2e8f0; border-radius: 0.5rem; transition: all 0.2s ease-in-out;"
                  placeholder="请简要描述退货原因..."
              ></textarea>
              <p v-if="!returnDescription.trim()" style="font-size: 0.75rem; color: #ef4444; margin-top: 0.25rem;">请填写退货说明</p>
            </div>

            <!-- 上传凭证 -->
            <div style="margin-bottom: 1rem;">
              <label style="display: block; font-size: 0.875rem; font-weight: 500; color: #475569; margin-bottom: 0.25rem;">上传凭证（最多3张）</label>
              <div  style="border: 2px dashed #e2e8f0; border-radius: 0.5rem; padding: 1rem; text-align: center; cursor: pointer; transition: border-color 0.2s ease-in-out;">
                <tui-upload
                  :server-url="'https://a.dderp.cn/mob/form/oss/uploadFilesWithSql?proname=UE0050'"
                  :width="200"
                  :height="200"
                  ref="tuiUploadReturnRef"
                  :max-count="3"
                  :preview="true"
                ></tui-upload>
<!--              <p v-if="tuiUploadReturnRef.value.imageList.length === 0" style="font-size: 0.75rem; color: #ef4444; margin-top: 0.25rem;">请上传凭证图片</p>-->
<!--              <p v-if="uploadError" style="font-size: 0.75rem; color: #ef4444; margin-top: 0.25rem;">{{ uploadError }}</p>-->
            </div>
            </div>
          </form>
        </div>
      </div>
    </main>

    <!-- 底部固定按钮 -->
    <div style="position: fixed; bottom: 0; left: 0; right: 0; background-color: #ffffff; border-top: 1px solid #e2e8f0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); z-index: 40; padding: 1rem;">
      <div style="display: flex; justify-content: space-between;height: 42px; height: 50px">
        <button @click="handleCancel" style=" flex: 1;  margin-right: 0.5rem; background-color: white; color: #3b82f6; border: 1px solid #3b82f6;  border-radius: 0.5rem; font-weight: 500; transition: all 300ms;">
          <i class="fa-solid fa-times" style="margin-right: 0.5rem;"></i> 取消
        </button>
        <button @click="handleSubmit" style="flex: 1; margin-left: 0.5rem; background-color: #ef4444; color: white;  border-radius: 0.5rem; font-weight: 500; transition: all 300ms;">
          <i class="fa-solid fa-check" style="margin-right: 0.5rem;"></i> 提交退货申请
        </button>
      </div>
    </div>

    <!-- 成功提示模态框 -->
    <div v-if="showSuccessModal" style="position: fixed; inset: 0; background-color: rgba(0, 0, 0, 0.5); z-index: 50; display: flex; align-items: center; justify-content: center; transition: opacity 0.3s ease-in-out;">
      <div style="background-color: #ffffff; border-radius: 1rem; padding: 1.5rem; max-width: 28rem; width: 100%; margin: 0 1rem; transform: scale(1); transition: transform 0.3s ease-in-out;">
        <div style="text-align: center;">
          <div style="width: 4rem; height: 4rem; background-color: #dcfce7; border-radius: 9999px; display: flex; align-items: center; justify-content: center; margin: 0 auto 1rem;">
            <i class="fa-solid fa-check" style="font-size: 1.5rem; color: #10b981;"></i>
          </div>
          <h3 style="font-size: 1.5rem; font-weight: 700; margin-bottom: 0.5rem;">退货处理成功</h3>
<!--          <p style="color: #475569; margin-bottom: 1.5rem;">您的退货申请已提交成功，我们将在1-3个工作日内处理您的申请</p>-->
          <button @click="closeSuccessModal" style="background-color: #dc2626; color: #ffffff; font-weight: 500; padding: 0.75rem 1rem; border-radius: 0.5rem; transition: background-color 0.2s ease-in-out; width: 100%;">
            确定
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, watch,onMounted } from 'vue';
import TuiUpload from "../tui-upload/tui-upload.vue";
import Input_number from "../input_number/input_number.vue";



export default {
  components: {Input_number, TuiUpload},
  props: {
    // 产品信息
    productInfo: {
      type: Object,
      default: () => ({})
    },
    // 工单信息
    workOrders: {
      type: Array,
      default: () => [
        { id: 'WO2025061700456', type: '量尺工单', status: '待处理', amount: '¥500.00', createTime: '2025-06-17 14:20' },
        { id: 'WO2025061800789', type: '设计工单', status: '处理中', amount: '¥300.00', createTime: '2025-06-18 10:15' }
      ]
    },
    // 初始退款金额
    initialRefundAmount: {
      type: Number,
      default: 0
    }
  },
  emits: {
    // 取消操作
    cancel: () => true,
    // 提交申请
    submit: (formData) => true,
    // 工单金额更新
    workOrderUpdated: (updatedOrders) => true
  },

  setup(props, { emit }) {
    // 退款金额
    const refundAmount = ref(props.initialRefundAmount || 0);

    // 退货原因
    const returnReason = ref('');
    const backInput = ref();
    // 退货说明
    const returnDescription = ref('');
    // 上传的文件预览
    const previewFiles = ref([]);
    // 文件上传输入框引用
    const uploadInput = ref(null);
    const tuiUploadReturnRef = ref();

    // 成功提示模态框显示状态
    const showSuccessModal = ref(false);
    // 正在编辑的工单索引
    const editingWorkOrderIndex = ref(-1);

    // 监听props.workOrders的变化，初始化工单数据
    watch(() => props.workOrders, (newOrders) => {
      if (newOrders && newOrders.length > 0) {
        // 初始化工单的编辑状态和输入金额
        const updatedOrders = newOrders.map(order => {
          return {
            ...order,
            inputAmount: order.srv_amount || 0,
            isEditing: false
          };
        });
        console.log('workOrders:', updatedOrders)
        workOrders.value = updatedOrders;
      }
    }, { deep: true, immediate: true });

    // 工单信息
    const workOrders = ref(
        props.workOrders.map(order => ({
          ...order,
          inputAmount: order.srv_amount || 0,
          isEditing: false
        }))
    );
    onMounted(() => {
      // 确保组件挂载后正确获取ref
      console.log('Upload input ref:', uploadInput.value);
      console.log(props.productInfo.back_num,'ldfsa')
      backInput.value = props.productInfo.back_num
    });

    // 更新退款金额显示
    const updateRefundAmountDisplay = (e) => {
      const inputElement = e.detail;
      let value = inputElement.value;
      // 移除非数字和小数点的字符
      value = value.replace(/[^0-9.]/g, '');

      // 确保只有一个点
      const parts = value.split('.');
      if (parts.length > 2) {
        value = parts[0] + '.' + parts.slice(1).join('');
      }

      // 保留两位小数
      if (parts[1] && parts[1].length > 2) {
        value = parseFloat(value).toFixed(2);
      }

      refundAmount.value = value;

      // 如果为空或无效值，设置为0.00
      const parsedValue = parseFloat(refundAmount.value);
      if (isNaN(parsedValue)) {
        // refundAmount.value = '0.00';
        uni.showToast({
          title: '请输入有效的金额',
          icon: 'none'
        });
      } else if (parsedValue > props.initialRefundAmount) {
        uni.showToast({
          title: '退款金额不能大于初始退款金额',
          icon: 'none'
        });
        // refundAmount.value = props.initialRefundAmount;
      } else {
        refundAmount.value = parsedValue;
      }
    };

    // 更新最终退款金额（订单金额 - 工单金额）
    const updateFinalRefundAmount = () => {
      const orderAmount = parseFloat(refundAmount.value);
      let totalWorkOrderAmount = 0;

      workOrders.value.forEach(order => {
        totalWorkOrderAmount += parseFloat(order.srv_amount);
      });

      const finalRefundAmount = (orderAmount - totalWorkOrderAmount).toFixed(2);
      console.log(`最终退款金额: ¥${finalRefundAmount}`);
    };

    // 编辑工单金额
    const editWorkOrder = (index) => {
      workOrders.value[index].inputAmount = parseFloat(workOrders.value[index].srv_amount);
      editingWorkOrderIndex.value = index;
    };
    //
    const changeBack = (value , event )  => {
/*     console.log(value,'value')
      console.log(event.detail.value,'event.detail.value')*/
      refundAmount.value = Number(value * props.productInfo.product_price)
    };

    // 取消编辑工单金额
    const cancelWorkOrderEdit = (index) => {
      editingWorkOrderIndex.value = -1;
    };

    // 保存工单金额
    const saveWorkOrderAmount = (index) => {
      const newAmount = parseFloat(workOrders.value[index].inputAmount).toFixed(2);
      workOrders.value[index].amount = `¥${newAmount}`;
      workOrders.value[index].isEditing = false;
      editingWorkOrderIndex.value = -1;
      updateFinalRefundAmount();

      // 触发工单更新事件
      emit('workOrderUpdated', workOrders.value);
    };

    // 打开文件选择框
    const openFileInput = () => {
      // 尝试获取原生 DOM 元素
      const realInput = uploadInput.value.$el || uploadInput.value;
      console.log(realInput.click(),'realInput')
      if (realInput && typeof realInput.click === 'function') {
        realInput.click();
      } else {
        console.error('未正确获取文件输入框 DOM');
      }
    };
    // 处理文件上传
    const handleFileUpload = () => {
      console.log('handleFileUpload', uploadInput.value)
      const files = uploadInput.value.files;
      if (files.length > 0) {
        previewFiles.value = [];
        const maxFiles = 3;
        const filesToProcess = files.length > maxFiles ? Array.from(files).slice(0, maxFiles) : files;

        for (let i = 0; i < filesToProcess.length; i++) {
          const file = filesToProcess[i];
          const reader = new FileReader();

          reader.onload = (e) => {
            previewFiles.value.push({
              file,
              url: e.target.result
            });
          };

          reader.readAsDataURL(file);
        }
      }
    };

    // 删除预览文件
    const removePreviewFile = (index) => {
      previewFiles.value.splice(index, 1);
    };

    // 处理取消操作
    const handleCancel = () => {
      emit('cancel');
    };

    // 表单提交
    const handleSubmit = () => {
      let isValid = true;

      if (!returnReason.value) {
        isValid = false;
        uni.showToast({
          title: '请填写退货原因',
          icon: 'none'
        });
      }
      if (refundAmount.value>props.initialRefundAmount) {
        isValid = false;
        uni.showToast({
          title: '退款金额不能大于初始退款金额',
          icon: 'none'
        });
      }

      if (!returnDescription.value.trim()) {
        isValid = false;
        uni.showToast({
          title: '请填写退货说明',
          icon: 'none'
        });
      }
      console.log(tuiUploadReturnRef.value.imageList)

      if (tuiUploadReturnRef.value.imageList.length === 0) {
        isValid = false;
        uni.showToast({
          title: '请上传凭证',
          icon: 'none'
        });
      }

      if (isValid) {
        // 组装表单数据
        const formData = {
          refundAmount: refundAmount.value,
          returnReason: returnReason.value,
          returnDescription: returnDescription.value,
          previewFiles: tuiUploadReturnRef.value.imageList,
          workOrders: workOrders.value,
          back_num:backInput.value
        };

        // 触发提交事件
        emit('submit', formData);
      }
    };

    // 关闭成功提示模态框
    const closeSuccessModal = () => {
      showSuccessModal.value = false;
      setTimeout(() => {
        emit('cancel'); // 提交成功后返回
      }, 300);
    };

    return {
      refundAmount,
      workOrders,
      returnReason,
      backInput,
      changeBack,
      returnDescription,
      previewFiles,
      uploadInput,
      showSuccessModal,
      editingWorkOrderIndex,
      tuiUploadReturnRef,
      updateRefundAmountDisplay,
      updateFinalRefundAmount,
      editWorkOrder,
      cancelWorkOrderEdit,
      saveWorkOrderAmount,
      openFileInput,
      handleFileUpload,
      removePreviewFile,
      handleCancel,
      handleSubmit,
      closeSuccessModal
    };

  }
};
</script>

<style scoped>
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}
</style>